"use client";

import type { Role } from "@/lib/api/system/role.d";
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
  ProTableProps,
} from "@ant-design/pro-components";
import { Button, Dropdown, message, Popconfirm, Space, Tag } from "antd";
import { useRouter } from "next/navigation";
import { useRequest } from "ahooks";
import { useRef } from "react";
import { deleteRoleApi, getRoleListApi } from "@/lib/api/system/role";
import { EllipsisOutlined } from "@ant-design/icons";

export default function Page() {
  const router = useRouter();
  const actionRef = useRef<ActionType>();

  const { run: deleteRole } = useRequest(deleteRoleApi, {
    manual: true,
    onSuccess: () => {
      message.success("删除成功");
      actionRef.current?.reload();
    },
    onError: () => {
      message.error("删除失败");
    },
  });

  const colums: ProColumns<Role>[] = [
    {
      title: "角色名称",
      dataIndex: "roleName",
      key: "roleName",
    },
    {
      title: "权限字符",
      dataIndex: "roleKey",
      key: "roleKey",
    },
    {
      title: "显示顺序",
      dataIndex: "roleSort",
      key: "roleSort",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      valueEnum: {
        "0": "启用",
        "1": "停用",
      },
      render: (_, record) => (
        <Tag color={record.status === "0" ? "green" : "red"}>
          {record.status === "0" ? "正常" : "停用"}
        </Tag>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      valueType: "dateTime",
      width: 150,
      hideInSearch: true,
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => editHandler(record.roleId)}>
            修改
          </Button>
          <Popconfirm
            title="确定删除吗？"
            description="删除后将无法恢复！"
            onConfirm={() => {
              deleteRole(record.roleId);
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
          <Dropdown
            trigger={["click"]}
            menu={{
              items: [
                {
                  label: "数据权限",
                  key: "resetPassword",
                },
                {
                  label: "分配用户",
                  key: "assignRole",
                },
              ],
            }}
          >
            <Button variant="link" color="pink">
              <EllipsisOutlined />
            </Button>
          </Dropdown>
        </Space>
      ),
    },
  ];

  const proTableProps: ProTableProps<Role, any> = {
    columns: colums,
    rowKey: "roleId",
    pagination: {
      pageSize: 10,
    },
    headerTitle: "角色列表",
    expandable: {
      defaultExpandAllRows: true,
    },
    actionRef: actionRef,
    options: {
      fullScreen: true,
    },
    toolBarRender: () => {
      return [
        <Button onClick={() => addHandler()} key="add" type="primary">
          新增
        </Button>,
      ];
    },
    request: async (params) => {
      const res = await getRoleListApi(params);

      return {
        data: res.rows,
        total: res.total,
        success: true,
      };
    },
    onRequestError(e) {
      message.error(e.message);
    },
  };

  const addHandler = () => {
    router.push(`role/add`);
  };

  const editHandler = (roleId: string) => {
    router.push(`role/edit?roleId=${roleId}`);
  };

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <ProTable {...proTableProps}></ProTable>
    </PageContainer>
  );
}
